package com.demoo.zjsu.filter.aop;

import com.demoo.zjsu.dao.smartwebsite.SmartWebDAO;
import com.demoo.zjsu.filter.CodeInterceptor;
import com.demoo.zjsu.filter.UserInfoInterceptor;
import com.demoo.zjsu.string.AOPStrings;
import com.demoo.zjsu.util.ExceptionToString.ExceptionLog;
import com.demoo.zjsu.util.javamail.MailSenderThread;
import com.demoo.zjsu.util.javamail.SimpleMailSender;
import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by jshjsh on 2016/8/13.
 */

@Component
@Aspect
public class UserInfoAop {

    private static long time = 0;

    Logger logger = Logger.getLogger(getClass());

    @AfterThrowing(value = "execution(* com.demoo.zjsu.controller..*(..))", throwing = "Ex")
    public void controllerWatcher(Exception Ex){
        String exception = ExceptionLog.toString(Ex);
       compareTime(exception, AOPStrings.CONTROLLER);
        logger.error(AOPStrings.CONTROLLER+exception);
        ExceptionLog.destory();
    }

    @AfterThrowing(value = "execution(* com.demoo.zjsu.service.smartwebsite.Quetz.*(..))", throwing = "Ex")
    public void serviceWatcher(Exception Ex){
        String exception = ExceptionLog.toString(Ex);
        compareTime(exception, AOPStrings.SERVICE);
        logger.error(AOPStrings.SERVICE+exception);
        ExceptionLog.destory();
    }

    public void compareTime(String exception, String type){
        long timeNow = System.currentTimeMillis();
        if (timeNow-time > 1000*60*60){
            MailSenderThread mailSenderThread = new MailSenderThread("工程出错啦！"+type
                    , "错误代码如下:\n"+exception);
            new Thread(mailSenderThread).start();
        }
        time = timeNow;
    }
}
